import time
import board
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

ble = BLERadio()
uart = UARTService()
advertisement = ProvideServicesAdvertisement(uart)
#advertisement.complete_name = "CPY_TEMP"
advertisement.short_name = "CPY_TEMP"
advertisement.connectable = True

import uctypes
from uctypes import BF_POS, BF_LEN
from uctypes import UINT32, BFUINT32, BFUINT16, BFUINT8, struct
#import time

# EMU内存映射基础地址
EMU_ADDR_BASE =0x50004000

# EMU温度数据寄存器地址偏移量
EMU_ADDR_TEMP_OFFSET = 0x088

# EMU状态数据寄存器地址偏移量
EMU_ADDR_STATUS_OFFSET = 0x084

# EMU命令寄存器地址偏移量
EMU_ADDR_CMD_OFFSET = 0x070

# EMU 温度传感器数据和状态数据结构
EMU_LAYOUT = {
    "EMU_TEMP": (
        EMU_ADDR_TEMP_OFFSET,
        {
            "TEMP": 2 << BF_POS | 9 << BF_LEN | BFUINT32,
            "TEMPLSB": 0 << BF_POS | 2 << BF_LEN | BFUINT32,
            "TEMPAVG": 18 << BF_POS  | 9 << BF_LEN | BFUINT32,
            "TEMPAVGLSB": 16 << BF_POS | 2 << BF_LEN | BFUINT32,
        }),
    "EMU_STATUS": (
        EMU_ADDR_STATUS_OFFSET,
        {
            "TEMPACTIVE": 2 << BF_POS | 1 << BF_LEN | BFUINT8,
            "TEMPAVGACTIVE": 3 << BF_POS | 1 << BF_LEN | BFUINT8,
        }),
    }

# 输出 EMU_LAYOUT 的size
#print(uctypes.sizeof(EMU_LAYOUT))

def say(n):
    print("[:.2f]".format(n))

# EMU_CMD 内存映射
emu_cmd = uctypes.bytearray_at(EMU_ADDR_BASE+EMU_ADDR_CMD_OFFSET, 1)

while True:
    ble.start_advertising(advertisement)
    print("Waiting to connect")
    while not ble.connected:
        pass
    print("Connected")
    
    #while True:
    while ble.connected:
        # 发送 EMU_CMD_TEMPAVGREQ 命令
        emu_cmd[0] = emu_cmd[0] | 0x10

        # emu数据读取结构
        emu = struct(EMU_ADDR_BASE, EMU_LAYOUT)

        # 输出 EMU 温度传感器测量状态值
        #print(emu.EMU_STATUS.TEMPACTIVE, emu.EMU_STATUS.TEMPAVGACTIVE)

        # 当前温度值
        T1 = emu.EMU_TEMP.TEMP
        T2 = emu.EMU_TEMP.TEMPLSB
        Tk = T1 + T2/4
        Tc = Tk - 273.15
        #print([T1, T2, Tk, Tc])
        
        # 平均温度值
        T1 = emu.EMU_TEMP.TEMPAVG
        T2 = emu.EMU_TEMP.TEMPAVGLSB
        Tavgk = T1 + T2/4
        Tavgc = Tavgk - 273.15
        #print([T1, T2, Tavgk, Tavgc])

        print("温度平均值: %0.2f, 温度当前值: %0.2f" % (Tavgc, Tc))

        result = "%0.2f,%0.2f\n" % (Tavgc, Tc)
        uart.write(result.encode("utf-8"))

        time.sleep(0.5)
